package com.enjoy.concurrent.ch1.pool;

import java.sql.Connection;
import java.sql.Statement;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {

    private static final DBPool pool = new DBPool(10);
    private static CountDownLatch latch = null;

    public static void main(String[] args) throws InterruptedException {

        int threadCount = 50;
        latch = new CountDownLatch(threadCount);

        // 每个线程操作次数
        int count = 20;

        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();
        for (int i = 0; i < threadCount; i++) {
            new Thread(new Worker(count, got, notGot), "worker" + i).start();
        }


        latch.await();

        System.out.println("threadCount*count = " + threadCount * count);

        System.out.println("got = " + got.get());

        System.out.println("notGot = " + notGot.get());
    }

    private static class Worker implements Runnable {
        int count;
        AtomicInteger got;
        AtomicInteger notGot;

        public Worker(int count, AtomicInteger got, AtomicInteger notGot) {
            this.count = count;
            this.got = got;
            this.notGot = notGot;
        }

        @Override
        public void run() {
            for (int i = 0; i < count; i++) {
                Connection connection = null;
                try {
                    connection = pool.fetchConnection(100 * count);
                    if (connection != null) {
                        got.incrementAndGet();
                        try {
                            Statement statement = connection.createStatement();
                            System.out.println("statement = " + statement);
                            Thread.sleep(1000);
                            // 操作数据库
                            connection.commit();
                        } finally {
                            pool.releaseConnection(connection);

                        }
                    } else {
                        notGot.incrementAndGet();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            latch.countDown();
        }
    }
}
